﻿/*
 * Twipler - Twitter Web Client with features.
 *  
 *  Copyright (C) 2010. Ian Quigley
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details. 
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */
using System;
using System.Text;
using System.IO;
using System.Web;
using Twipler.App.Session;
using Twipler.Xtensions;

namespace Twipler.App.Render
{
    public class PublishTempFile : ISessionCleanup
    {
        public string FilePath;
        public string HttpPath;

        public PublishTempFile(string extension)
        {
            NewFilename(extension);
        }

        protected void NewFilename(string extension)
        {
            string filename = Guid.NewGuid().ToString() + extension;
            FilePath = Path.Combine(HttpContext.Current.Server.MapPath("gen"), filename);
            HttpPath = "gen/" + filename;                
        }

        public void Write(string content)
        {
            object[] dbg = Current.Log.EnterMethod("PublishTempFile.Write(" + FilePath + ")");

            Current.Log.Info("PublishTempFile.Write(" + FilePath + ")");

            using (FileStream writer = new FileStream(FilePath, FileMode.OpenOrCreate))
            {
                byte[] buffer = Encoding.UTF8.GetBytes(content);
                writer.Write(buffer, 0, buffer.Length);
            }

            Current.Log.ExitMethod(dbg);
        }

        public virtual void DeleteFileQuiet()
        {
            object[] dbg = Current.Log.EnterMethod("PublishTempFile.Delete(" + FilePath + ")");

            try
            {
                if (File.Exists(FilePath))
                    File.Delete(FilePath);                
            }
            catch
            {}

            FilePath = string.Empty;
            HttpPath = string.Empty;

            Current.Log.ExitMethod(dbg);
        }

        public void SessionEnd()
        {
            DeleteFileQuiet();
        }
    }
}
